import React, { memo, useRef } from 'react'
import type { FC, ReactNode } from 'react'
import classNames from 'classnames'
import dayjs from 'dayjs'
import { useNavigate } from 'react-router-dom'

import fetchData from '../../request/index'
import ThemeSelector from '../../components/Antd/ThemeSelector'
// import LanguageSelector from '../../components/Antd/LanguageSelector'
import CodeSelector from '../../components/Antd/CodeSelector'
import TitleName from '../../components/Antd/TitleName'
import LabelSelector from '../../components/Antd/LabelSelector'
import TimeSelector from '../../components/Antd/TimeSelector'
import Password from '../../components/Antd/Password'
import MarkDownEditor from '../../components/Bytemd'
import styles from './index.module.scss'
import '../../styles/iconfont.css'
import { useMySelector, useMyDispatch, MyShallEqual } from '../../store'
import {
  setIsShow,
  setIsOpen,
  setPassword,
  setCurrentTime
} from '../../store/modules/create'
import { setShareOrEdit } from '../../store/modules/success'
import { setExit } from '../../store/modules/codeall'

interface IProps {
  children?: ReactNode
}

const Create: FC<IProps> = () => {
  const {
    isShow,
    isOpen,
    password,
    title,
    endTime,
    codeAll,
    label,
    mdContent,
    theme,
    codeUrl,
    id,
    exit
  } = useMySelector(
    (state) => ({
      isShow: state.code.isShow,
      isOpen: state.code.isOpen,
      password: state.code.password,
      title: state.code.title,
      endTime: state.code.endTime,
      codeAll: state.codeall.codeAll,
      label: state.code.label,
      mdContent: state.success.mdContent,
      theme: state.success.theme,
      codeUrl: state.success.codeUrl,
      id: state.codeall.id,
      exit: state.codeall.exit
    }),
    MyShallEqual
  )

  const dispatch = useMyDispatch()
  const spanRef = useRef<HTMLSpanElement>(null)
  const navigate = useNavigate()

  const showMore = () => {
    if (spanRef.current) {
      const classList = spanRef.current?.classList
      if (isShow === false) {
        classList.remove('icon-youjiantou')
        classList.add('icon-xiangxia')
        dispatch(setIsShow(true))
      } else if (isShow === true) {
        classList.remove('icon-xiangxia')
        classList.add('icon-youjiantou')
        dispatch(setIsShow(!isShow))
      }
    }
  }

  const changePassword = () => {
    if (isOpen) return
    const length = Math.floor(Math.random() * 5) + 4 // 生成4到8位的长度
    const characters =
      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    let result = ''
    for (let i = 0; i < length; i++) {
      const randomIndex = Math.floor(Math.random() * characters.length)
      result += characters[randomIndex]
    }
    dispatch(setPassword(result))
  }

  const submitCheck = () => {
    if ((password.length < 4 || password.length > 8) && !isOpen) {
      alert('密码应该是长度4-8位')
      return
    }
    if (dayjs(endTime).isBefore(dayjs())) {
      const tag = window.confirm(
        `当前时间为${dayjs().format('YYYY-MM-DD HH:mm:ss')}\n过期时间早于提交时间可能会导致后续功能无法使用\n是否继续提交？`
      )
      if (!tag) return
    }
    const newCurrentTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
    dispatch(setCurrentTime(newCurrentTime))
    dispatch(setShareOrEdit(true))
    navigate('/success')
    fetchSubmit(newCurrentTime)
  }

  const fetchSubmit = async (newCurrentTime: string) => {
    const body = {
      id,
      codeAll,
      title,
      isOpen,
      password,
      currentTime: newCurrentTime,
      endTime,
      label,
      mdContent,
      theme,
      codeUrl
    }
    if (!exit) {
      dispatch(setExit(true))
      await fetchData('/submit', body, 'POST')
    } else {
      await fetchData('/update', body, 'POST')
    }
  }

  return (
    <div
      className={classNames(
        styles.container,
        theme === 'cyan' ? styles.cyan : theme === 'green' ? styles.green : ''
      )}
    >
      <div className={styles.title}>
        <div className={styles.red}></div>
        <div className={styles.yellow}></div>
        <div className={styles.green}></div>
        <span className={styles.text}>{title}</span>
        <div className={styles.theme}>
          <ThemeSelector />
        </div>
      </div>

      <CodeSelector />
      {/* <LanguageSelector /> */}
      {/* <CodeEditor /> */}

      <div className={styles.moresettings}>
        <div className={styles.moresettext} onClick={showMore}>
          <span className="iconfont icon-youjiantou" ref={spanRef}></span>
          更多设置
        </div>
        <div className={classNames(styles.detail, isShow ? '' : styles.isshow)}>
          <div className={styles.chooseptions}>
            <div className={styles.titlename}>
              <span>标题</span>
              <div className={styles.titlenameContent}>
                <TitleName />
              </div>
            </div>

            <div className={styles.label}>
              <span>标签</span>
              <div className={styles.chooselabel}>
                <LabelSelector />
              </div>
            </div>

            <div className={styles.outtime}>
              <span>过期时间</span>
              <div className={styles.chooseouttime}>
                <TimeSelector />
              </div>
            </div>
          </div>

          <div className={styles.markdown}>
            <MarkDownEditor />
          </div>
        </div>

        <div className={styles.footer}>
          <div className={styles.submit}>
            <div className={styles.openorpass}>
              <span
                className={classNames(isOpen && styles.isactive)}
                onClick={() => dispatch(setIsOpen(true))}
              >
                公开
              </span>
              <span
                className={classNames(!isOpen && styles.isactive)}
                onClick={() => dispatch(setIsOpen(false))}
              >
                加密
              </span>
              <div
                className={classNames(styles.submitbutton)}
                onClick={() => {
                  submitCheck()
                }}
              >
                提交
              </div>
            </div>
          </div>
          <div className={classNames(styles.password)}>
            <span className={styles.passtext}>密码</span>
            <div className={styles.inputpass}>
              <Password />
            </div>
            <span
              className={classNames('iconfont', 'icon-shuaxin')}
              onClick={changePassword}
            ></span>
          </div>
        </div>
      </div>
    </div>
  )
}

export default memo(Create)
